﻿using System.Collections.Generic;
using UnityEngine;

namespace SLG_Demo_0
{
	public class UnitControl : MonoBehaviour
	{
        /// <summary>
        /// 需要指定的，单位移动速度
        /// </summary>
		public int speed;

        //////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// 单位所在地图对象
        /// </summary>
        private MapObject _mapObject = null;

		/// <summary>
		/// 移动经过的路径点集合，注意，容器必须是顺序容器
		/// </summary>
		private List<Vector3> _listPathPoint = null;

		/// <summary>
		/// 当前要移动到的路径点集合下标
		/// </summary>
		private int _curPathPointIndex = -1;

		/// <summary>
		/// 是否移动结束
		/// </summary>
		private bool _bMoveOver = false;

		/// <summary>
		/// 为 true 表示完成一次寻路
		/// </summary>
		private bool _bSearch = false;

		/// <summary>
		/// 当前选中的 GameObject
		/// </summary>
		private GameObject _selectObj = null;

		/// <summary>
		/// 目标格子X坐标
		/// </summary>
		private int _destX = -1;

		/// <summary>
		/// 目标格子Y坐标
		/// </summary>
		private int _destY = -1;


		//////////////////////////////////////////////////////////////////////////
		// Use this for initialization
		void Start()
		{
			_listPathPoint = new List<Vector3>();

			if (_mapObject == null)
			{
				GameObject objMapDisplay = GameObject.Find("MapDisplay");
				if (objMapDisplay != null)
				{
					_mapObject = objMapDisplay.GetComponent<MapObject>();
				}
			}
		}

		void FixedUpdate()
		{
			//Move();

			MoveWithPath();

			MousePick();

			// 鼠标右键抬起
			if (Input.GetMouseButtonUp(1))
			{
				// 确定要移动的终点
				if (_selectObj != null)
				{
					Vector3Int cellPos = _mapObject.MapDisplay.MousePos2TilePos(Input.mousePosition);
					_destX = cellPos.x;
					_destY = cellPos.y;
					_bMoveOver = false;
				}
			}
		}

		private bool Search()
		{
			if (_selectObj == null)
			{
				return false;
			}

			if (_destX < 0 || _destY < 0 || _destX >= _mapObject.m_width || _destY >= _mapObject.m_height)
			{
				return false;
			}

			Vector2Int beginCellPos = _mapObject.MapDisplay.WorldToCell(_selectObj.transform.position);
			if (beginCellPos.x < 0 || beginCellPos.y < 0 || beginCellPos.x >= _mapObject.m_width || beginCellPos.y >= _mapObject.m_height)
			{
				return false;
			}

			if (_listPathPoint != null && _listPathPoint.Count > 0)
			{
				_listPathPoint.Clear();
			}

			CellData srcCellData = _mapObject.MapData.Cells[beginCellPos.x, beginCellPos.y];
			CellData dstCellData = _mapObject.MapData.Cells[_destX, _destY];

			List<CellData> lstCellData = new List<CellData>();
			bool bSearch = PathFinding.Instance.Search(_mapObject.MapData, srcCellData, dstCellData, lstCellData);
			if (bSearch)
			{
				for (int iSearch = 0; iSearch < lstCellData.Count; ++iSearch)
				{
					Vector3 pathpoint = _mapObject.MapDisplay.CellToWorld(lstCellData[iSearch].Row, lstCellData[iSearch].Col);
					_listPathPoint.Add(pathpoint);
				}

				return true;
			}
			else
			{
				return false;
			}
		}

		private void MoveWithPath()
		{
			if (!_bSearch)
			{
				// 寻路若成功，路径点集合中必定至少有一个路径点可移动。
				// 否则这次寻路就是无意义的
				bool bSuccess = Search();
				if (bSuccess && _listPathPoint.Count > 0)
				{
					_bSearch = true;
					_curPathPointIndex = 0;
				}
				else
				{
					return;
				}
			}

			if (_bSearch && _listPathPoint.Count > 0 && !_bMoveOver)
			{
				Vector3 pathPoint = _listPathPoint[_curPathPointIndex];
				_selectObj.transform.position = Vector3.MoveTowards(_selectObj.transform.position, pathPoint, Time.fixedDeltaTime * speed);
				float distance = Vector3.Distance(pathPoint, _selectObj.transform.position);
				if (distance <= 0.0f)
				{
					if (_curPathPointIndex >= _listPathPoint.Count - 1)
					{
						// 当前移动路径点已经是最后一个，到这个路径点距离为0，移动可以结束了
						// 重置各种标记位。清空路径点集合
						_bMoveOver = true;
						_bSearch = false;
						_curPathPointIndex = -1;
						_listPathPoint.Clear();
						_destX = -1;
						_destY = -1;
					}
					else
					{
						// 已经移动到当前路径点，尝试移动到下一个路径点
						++_curPathPointIndex;
					}
				}

				Debug.Log("m_TestUnit_0 Pos: (" + transform.position.x + ", " + transform.position.y + ")");
			}
		}

		/*void MobilePick()
		{
			if (Input.touchCount != 1)
				return;

			if (Input.GetTouch(0).phase == TouchPhase.Began)
			{
				RaycastHit hit;
				Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);

				if (Physics.Raycast(ray, out hit))
				{
					Debug.Log(hit.transform.name);
					//Debug.Log(hit.transform.tag);
				}
			}
		}*/

		/// <summary>
		/// 点击选择单位
		/// </summary>
		void MousePick()
		{
			if (Input.GetMouseButtonUp(0))
			{ 
				Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
				Vector2 mousePos2D = new Vector2(mousePos.x, mousePos.y);

				// TODO：暂时不考虑多个单位叠加的情况
				// 若出现多个单位叠加，则应该用 Physics2D.RaycastAll(...)
				// 但同一时刻只可能选择一个单位
				RaycastHit2D hit = Physics2D.Raycast(mousePos2D, Vector2.zero);
				if (hit.collider != null)
				{
					GameObject hitobj = hit.collider.gameObject;

					// 只要原来的 m_SelectObj 没有再次被选中，将其置为白色
					if (_selectObj != null && _selectObj != hitobj)
					{
						_selectObj.GetComponent<SpriteRenderer>().color = Color.white;
					}

					// 选中了某个单位......
					if (hitobj != null)
					{
						_selectObj = hitobj;
						// 方便显示......
						SpriteRenderer spriterenderer = hitobj.GetComponent<SpriteRenderer>();
						spriterenderer.color = Color.green;
					}
				}
			}
		}
	}
}

